﻿/**

 @Name：swui.menu 开始菜单模块
 @Author：Zxq
 @License：MIT
    
 */
layui.define(['jquery', 'element', 'layer', 'swui'], function (exports) {
    "use strict";

    var $ = layui.jquery,
        element = layui.element;

    //开始菜单构造函数
    var Menu = function () {
        swui.baseObject.call(this, 'menu');
        this.menus = {};
        this.elems = {};
    };

    Menu.prototype = {
        //初始化html元素及事件
        render: function (callback) {
            var othis = this,
                buttons = othis.configs.buttons || [];
            othis.elem = othis.configs.elem || $('.swui-start');
            //左侧区域
            othis.elems.leftMenu = $('<div class="swui-start-left bottom"></div>').appendTo(othis.elem);
            //左侧区域按钮及事件
            $(buttons).each(function (index, item) {
                item.elem = $('<div class="swui-start-item" data-text="'+item.name+'">'+othis.getIconHtml(item.icon)+'</div>').appendTo(othis.elems.leftMenu);
                othis.resetEvent('click', item.elem, function(e){
                    if (othis.Utils.isFunction(item.handler))
                        item.handler.call(this);
                });
            });
            
            //菜单区域
            othis.elem.append('<div class="swui-start-center"><div class="layui-side-scroll"><ul class="swui-menu layui-nav layui-nav-tree" lay-filter="swuimenu"></ul></div></div>');
            //磁贴区域
            othis.elem.append('<div class="swui-start-right"><div class="layui-side-scroll"><div class="swui-nav-tile"></div></div></div>');
            othis.elems.menu = othis.elem.find('.swui-start-center ul.swui-menu');//菜单部分
            othis.elems.tile = othis.elem.find('.swui-start-right div.swui-nav-tile');//磁贴部分

            othis.setData({urlcode:'uimenu'}, function (data) {
                othis.data = data;
                othis.renderElems();
                //调用渲染完毕的回调函数
                if (othis.Utils.isFunction(callback))
                    callback.call(this, othis);
            });

        }
        ,renderElems: function () {
            if (this.data === null) return;
            var othis = this;
            $(this.data.menus).each(function (index, item) {
                othis.addMenuItem(item);
            });

            $(this.data.tiles).each(function (index, item) {
                othis.addTile(item);
            });
            othis.locaTile();
            
            othis.resetEvents();
        }
        ,resetEvents: function (){
            var othis = this,
                contextmenu = othis.configs.contextmenu,
                tilemenu = othis.configs.tilemenu;
            //绑定开始菜单左边按钮鼠标悬浮事件
            othis.resetEvent('mouseover', othis.elems.leftMenu.find('>.swui-start-item'), function (event) {
                var text = $(event.currentTarget).data('text');
                var x = event.clientX - 20;
                var y = event.clientY - 50;
    
                if (x < 0) x = 0;
    
                var html = '<div class="leftbtnhovertext" style="top:' + y + 'px;left:' + x + 'px;">' + text + '<div>';
                $(document.body).append(html);
            });
            //绑定开始菜单左面按钮鼠标移出事件
            othis.resetEvent('mouseout', othis.elems.leftMenu.find('>.swui-start-item'), function () {
                $('.leftbtnhovertext').remove();
            });
            
            //初始化layui的element（可以从新监听点击事件）
            element.init('nav', 'swuimenu');
            element.on('nav(swuimenu)', function(){
                if (othis.Utils.isFunction(othis.configs.events.click)){
                    var code = $(this).closest('li,dd').data('code');
                    var option = othis.menus[code];
                    if (!option || !option.url) return;
                    othis.configs.events.click.call(this, option);
                }
            });
            //菜单右键事件
            othis.resetEvent('mouseup', 'li[data-code], dd[data-code]', function(e) {
                if (e.button == 2) {
                    if ($(this).children('.layui-nav-child').length > 0) return;
                    var pos = {left: e.clientX+'px',top: e.clientY+'px'};
                    var code = $(this).data('code');
                    othis.ContextMenu(null, contextmenu, 'menu-contextmenu', pos, othis.menus[code]);
                }
                othis.sp(e);
            }, othis.elems.menu);
            //磁贴点击事件
            othis.resetEvent('click', '>.swui-tilebox .swui-tile', function(){
                if (othis.Utils.isFunction(othis.configs.events.click)){
                    var code = $(this).data('code');
                    var option = othis.menus[code];
                    if (!option || !option.url) return;
                    othis.configs.events.click.call(this, option);
                }
            },this.elems.tile);
            //磁贴右键事件
            othis.resetEvent('contextmenu', '>.swui-tilebox .swui-tile', function(e){
                var pos = {left: e.clientX+'px',top: e.clientY+'px'};
                var code = $(this).data('code');
                othis.ContextMenu(null, tilemenu, 'menu-contextmenu', pos, othis.menus[code]);
            },this.elems.tile);
        }
        //添加菜单(及子菜单)
        ,addMenuItem: function (option, callback) {
            if (!option || !option.code) return;
            var othis = this;
            var html,menuItem;
            if (!option.parent) {//顶级菜单
                html = '<li data-code="'+option.code+'" class="layui-nav-item'+(option.extend ? ' layui-nav-itemed' : '')+'"><a>';
                html += '<div class="swui-menu-icon">' + othis.getIconHtml(option.icon) + '</div>';
                html += '<span class="swui-menu-name">' + option.name + '</span></a></li>';
                menuItem = $(html).appendTo(othis.elems.menu);
            }
            else {
                var parentnode = this.elems.menu.find('li.layui-nav-item[data-code="'+option.parent+'"],dl.layui-nav-child dd[data-code="'+option.parent+'"]');
                if (parentnode.length === 0) return;//未找到父菜单
                var parent = parentnode.children('dl.layui-nav-child');
                parent.length===0 && (parent = $('<dl class="layui-nav-child"></dl>').appendTo(parentnode));
                html = '<dd data-code="'+option.code+'"'+(option.extend ? ' class="layui-nav-itemed"' : '')+'><a>';
                html += '<div class="swui-menu-icon">' + othis.getIconHtml(option.icon) + '</div>';
                html += '<span class="swui-menu-name">' + option.name + '</span></a></dd>';
                menuItem = $(html).appendTo(parent);
            }
            othis.menus[option.code] = option;
            if (option.childrens) {
                $(option.childrens).each(function (index, item){
                    othis.addMenuItem(item);
                })
            }
            if (othis.Utils.isFunction(callback)) {
                callback(menuItem);
            }
            return menuItem;
        }
        //移除菜单(及子菜单)
        ,removeMenuItem: function (option, callback) {
            var menuItem;
            if (this.Utils.isString(option))
                menuItem = this.elems.menu.find('.layui-nav-item[data-code="'+option+'"]');
            else if (!option.code) return;
            else menuItem = this.elems.menu.find('.layui-nav-item[data-code="'+option.code+'"]');
            if (menuItem.length > 0) {
                menuItem.remove();
            }
            if (this.Utils.isFunction(callback)) {
                callback(menuItem);
            }
        }
        //添加磁贴(组或单项)
        ,addTile: function (option, callback) {
            if (!option || !option.code) return;
            var othis = this;
            if (option.items) {//添加一组磁贴
                var tile = $('<div class="swui-tilebox"></div>').appendTo(othis.elems.tile);
                tile.append('<div class="swui-tilebox-head">'+option.title+'</div>');
                var item = $('<div class="swui-tilebox-body" data-code="'+option.code+'"></div>').appendTo(tile);
                for (var i=0;i<option.items.length;i++){
                    option.items[i].parent = item;
                    othis.additem(option.items[i]);
                }
            }
            else if (option.icon || option.content) {//添加单个磁贴
                othis.additem(option);
            }
            if (othis.Utils.isFunction(callback)) {
                callback();
            }
        }
        //添加磁贴项(单个)
        ,additem: function (option, callback) {
            if (!option || !option.code || !option.parent) return;
            var othis = this;
            var parent;
            if (this.Utils.isString(option.parent)) {
                parent = othis.elems.tile.children('div[data-code="'+option.parent+'"]');
                if (parent.length === 0)
                    return;
            }
            else parent = option.parent;
            var html = '<div class="swui-tile swui-tile-'+(option.size ? option.size : 'normal')+'" data-code="'+option.code+'">'+function(){
                if (option.icon) {
                    return othis.getIconHtml(option.icon);
                }
                else if (option.content) {
                    return option.content;
                }
                else return '';
            }()+'<span>'+option.title+'</span></div>';
            var item = $(html).appendTo(parent);
            if (othis.Utils.isFunction(callback)) {
                callback(item);
            }
        }
        //移除磁贴(组或单项)
        ,removeTile: function (option, callback) {
            var tileItem;
            if (this.Utils.isString(option))
                tileItem = this.elems.tile.find('div[data-code="'+option+'"]');
            else if (!option.code) return;
            else tileItem = this.elems.tile.find('div[data-code="'+option.code+'"]');
            if (tileItem.length > 0) {
                if (tileItem.is('.swui-tilebox-body'))
                    tileItem.parent().remove();
                else tileItem.remove();
            }
            this.locaTile();
            if (this.Utils.isFunction(callback)) {
                callback(tileItem);
            }
        }
        //磁贴定位
        ,locaTile: function(){
            var left = 0,right = 0;
            var size = this.configs.Size;
            this.elems.tile.children().each(function(){
                var obj = $(this)[0];
                switch (size) {
                    case 'xs':
                    case 'sm':
                        $(obj).css('marginTop', '');
                        break;
                    default:
                        if (obj.offsetLeft === 0) {
                            if (obj.offsetTop - left != 0) {
                                var top = parseInt($(obj).css('marginTop'));
                                $(obj).css('marginTop', top+left-obj.offsetTop);
                            }
                            left += obj.offsetHeight;
                        }
                        else {
                            if (obj.offsetTop - right != 0) {
                                var top = parseInt($(obj).css('marginTop'));
                                $(obj).css('marginTop', top+right-obj.offsetTop);
                            }
                            right += obj.offsetHeight;
                        }
                        break;
                }
            })
        }
        //改变开始菜单尺寸
        , changeSize: function (size) {
            if (this.configs.Size === size) return;
            this.configs.Size = size;
            if (this.elem.attr('class')) {
                this.elem.attr('class', this.elem.attr('class').replace(/\bswui-start-size-.{3}/g, '').replace(/(^\s*)|(\s*$)/g, ""));  //去掉swui-start-size-的class后去除两边空格
            }
            switch (size) {
                case 'xs':
                    this.elem.addClass('swui-start-size-xs');
                    break;
                case 'sm':
                    this.elem.addClass('swui-start-size-sm');
                    break;
                default:
                    break;
            }
            this.locaTile();
        }
    };

    var menu = new Menu();

    swui.menu = menu;

    exports(menu.MOD_NAME, {});

    delete layui.menu;
});